<script setup lang="ts">
import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import {
  genModelAddApi,
  genModelEditApi,
  genModelQueryByIdApi,
} from '#/api/gen/model';
import { genModelClassifyQueryListApi } from '#/api/gen/modelType';

import ImportTableModal from './modules/ImportTableModal.vue';

const record = ref({});
const confirmLoading = ref(false);

// 下划线转驼峰
function toCamelCase(str: string): string {
  return str.replaceAll(/([-_][a-z])/gi, ($1) => {
    return $1.toUpperCase().replace('-', '').replace('_', '');
  });
}

const [Form, formApi] = useVbenForm({
  showDefaultActions: false,
  wrapperClass: 'grid-cols-1',
  commonConfig: {
    boolean: true,
    labelWidth: 90,
    componentProps: {
      class: 'w-full',
    },
  },
  schema: [
    {
      component: 'ApiSelect',
      componentProps: {
        afterFetch: (data) => {
          // 筛选使用中的数据源
          const filteredData = data.filter((item) => item.isShow === 0);
          return filteredData.map((item: any) => ({
            label: item.name,
            value: item.id,
          }));
        },
        api: genModelClassifyQueryListApi,
        placeholder: '请选择模型分类',
        allowClear: true,
      },
      fieldName: 'modelClassifyId',
      label: '模型分类',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入模型名称',
      },
      fieldName: 'modelName',
      label: '模型名称',
      help: '模型名称就是数据库表注释,也就是功能名',
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入模型编码',
      },
      fieldName: 'modelCode',
      label: '模型编码',
      help: '模型编码需要对应数据库表名',
      rules: 'required',
      dependencies: {
        triggerFields: ['id'],
        disabled(values) {
          return !!values.id;
        },
        // rules() {
        //   return z
        //     .string({ required_error: '请输入模型编码' })
        //     .refine(async (value) => {
        //       if (!value) return true;
        //       return !(await genModelExistModelNameApi({
        //         modelName: value,
        //       }));
        //     }, '模型编码已存在');
        // },
      },
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入业务路径',
      },
      fieldName: 'businessPath',
      label: '业务路径',
      help: '业务路径就是对应API的路径,如user',
      rules: 'required',
      dependencies: {
        triggerFields: ['modelCode'],
        show(values, formApi) {
          if (values?.modelCode) {
            formApi.setFieldValue(
              'businessPath',
              toCamelCase(values?.modelCode),
            );
          }
          return true;
        },
      },
    },
    {
      component: 'RadioGroup',
      defaultValue: 'single',
      rules: 'required',
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        options: [
          {
            label: '流程模型',
            value: 'single',
          },
          {
            label: '树模型',
            value: 'tree',
          },
        ],
      },
      fieldName: 'modelCharacter',
      help: '树模型需要包含pid,is_leaf',
      label: '模型特性',
    },
  ],
});

const [Modal, modalApi] = useVbenModal({
  title: '模型',
  confirmLoading,
  onCancel: () => {
    modalApi.close();
  },
  onConfirm: onSubmit,
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      record.value = modalApi.getData<Record<string, any>>();
      modalApi.setState({
        title: `${record.value.id ? '编辑' : '新增'}模型`,
      });
      if (record.value.id) {
        initFun();
      } else {
        formApi.setValues(record.value, false);
      }
    }
  },
});
async function initFun() {
  const res = await genModelQueryByIdApi({ id: record.value.id });
  await formApi.setValues(res, false);
}
async function onSubmit() {
  confirmLoading.value = true;
  const { valid } = await formApi.validate();
  const values = await formApi.getValues();
  if (valid) {
    if (record.value.id) {
      const msg = await genModelEditApi(values);
      message.success(msg);
      confirmLoading.value = false;
      await modalApi.close();
    } else {
      const msg = await genModelAddApi(values);
      message.success(msg);
      confirmLoading.value = false;
      await modalApi.close();
    }
  }
}
const [ImportModal, importModalApi] = useVbenModal({
  connectedComponent: ImportTableModal,
  onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      const importParams = importModalApi.getData<Record<string, any>>();
      formApi.setValues(importParams, false);
    }
  },
});

function importTable() {
  importModalApi.open();
}
</script>

<template>
  <Modal>
    <ImportModal class="w-[50%]" />
    <Form>
      <template #modelName="slotProps">
        <a-input-group compact>
          <a-input v-bind="slotProps" style="width: calc(100% - 200px)" />
          <a-button
            type="primary"
            :disabled="
              record.id !== '' && record.id !== undefined && record.id !== null
            "
            @click="importTable()"
          >
            导入表
          </a-button>
        </a-input-group>
      </template>
    </Form>
  </Modal>
</template>
